import React from 'react';
import './goodsrelevance.less';
import { Layout, Breadcrumb, Icon, Button, Table, Checkbox, Modal, Input, Select, Form, Pagination, message, InputNumber, Popconfirm } from 'antd';
import $ from 'jquery';
import Config from '../../common/config';
import { Link, hashHistory } from 'react-router';
import RelationProduct from './relationproduct';
import { fail } from 'assert';

const FormItem = Form.Item;
const config = new Config()
const { Header, Content, Footer, Sider } = Layout;
const Option = Select.Option;
const InputGroup = Input.Group;
const { TextArea } = Input;
const token = sessionStorage.getItem('token')

class RegForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            relationid: this.props.params.relationid.split('&')[0],//关联ID
            relationname: this.props.params.relationid.split('&')[1],//关联名称
            relationstatus: this.props.params.relationid.split('&')[2],//关联状态 0-关闭 1-启用
            pageindex: this.props.params.relationid.split('&')[3],
            relationdetaillist: [],//新增/修改关联列表
            relationsort: '',//关联排序
            checked: true,//是否开启
            productvisible: false,
            products: new Array(10).fill(undefined),
            isexistence: '',//是否存在
            addIndex: 0,//记录保存按钮点击了几次
        }
    }

    componentDidMount() {
        if (this.state.relationid != 0) {
            //console.log(this.state.relationstatus);
            //关联名称
            const form = this.props.form;
            form.setFieldsValue({ txt_RelationName: this.state.relationname });
            //关联状态
            if (this.state.relationstatus == 0) {
                this.setState({
                    checked: false,
                })
            } else {
                this.setState({
                    checked: true,
                })
            }
            this.GetProductListByRelationid();
        }
    }

    //关联商品列表
    GetProductListByRelationid() {
        console.log('关联ID', this.state.relationid)
        $.ajax({
            url: `${config.JuseProduct}/relations/detail`,
            type: "get",
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                relationId: this.state.relationid,
            },
            async: true,
            success: res => {
                console.log("新增/修改关联列表：", res)
                if (res.code === 200) {
                    this.setState({
                        relationdetaillist: res.data
                    });
                } else {
                    message.config({
                        top: 50,
                    });
                    message.error('商品关联列表加载失败，请返回重新操作', 2);
                }
            }
        });
    }

    //添加商品的对话框组件
    addProductModal() {
        const { relationdetaillist } = this.state;
        let flag = true;
        for (let value of relationdetaillist) {
            if (!value) {
                flag = false;
                break;
            }
        }
        if (flag && relationdetaillist.length === 10) {
            message.error('添加商品数已达到上限10个，请先移出再添加', 2);
        } else {
            let productids = '';
            if (relationdetaillist.length > 0) {
                relationdetaillist.forEach(item => {
                    productids += "," + item.productid;
                });
                productids = productids.substring(1)
            } else {
                productids = 0;
            }
            this.refs.relationproduct.state.productid = productids//子页面的productid
            this.setState({
                productvisible: true,
            }, () => this.refs.relationproduct.getProductList())//调用子页面的方法
        }
    }

    //确认添加商品
    addProduct(products) {
        const newArr = [];
        let relationdetaillist = this.state.relationdetaillist;
        products.forEach(item => {
            let result = false
            relationdetaillist.forEach(value => {
                if (item.productId === value.productId) {
                    result = true
                    newArr.push(item);
                }
            })
            if (!result) {
                newArr.push(item)
            }
        })
        relationdetaillist = relationdetaillist.concat(newArr)
        this.setState({
            productvisible: false,
            products,
            relationdetaillist
        })
    }
    //取消添加商品
    cancelProduct() {
        this.setState({
            productvisible: false
        })
    }

    //是否开启的改变事件
    onChangeRelation(e) {
        this.setState({ checked: e.target.checked });
    }

    //关联排序的改变事件
    numberChange(record, e) {
        // e.target.value = e.target.value.replace(/[^\d]/g, ''); //清除"数字"以外的字符
        let g = /^([1-9]{1}|10)$/;//只许输入1-10的正整数
        if (!g.test(e.target.value)) {
            e.target.value = '';
        }
        let relationdetaillist = this.state.relationdetaillist;
        // let relationdetaillist = [].concat(this.state.relationdetaillist);
        let index = -1;
        let bool = false;
        relationdetaillist.forEach((item, i) => {
            // console.log('判断', item.relationsort == e.target.value, item.relationsort, e.target.value)
            if (item.productId == record.productId) index = i;//判断输入的序号和已存在的序号相不相同
            if (e.target.value) {
                if (item.relationSort == e.target.value) bool = true;
            }
        })
        if (bool) {
            this.state.isexistence = '已存在该序号';
            return message.error('已存在该序号');
        } else {
            this.state.isexistence = '';
            // console.log(typeof index);
            if (index != -1) {
                relationdetaillist[index].relationSort = e.target.value;//验证成功为排序属性赋值
            }
            this.setState({ relationdetaillist })
        }
    }

    //产品规格改变事件
    relationspeciChange(record, e) {
        //console.log(e.target.value)
        let relationdetaillist = this.state.relationdetaillist;
        let index = 0;
        relationdetaillist.forEach((item, i) => {
            if (item.productId == record.productId) index = i;
        })
        relationdetaillist[index].relationSpec = e.target.value;
        this.setState({ relationdetaillist })
    }

    //移除确定
    confirmRelation(record, e) {
        let relationdetaillist = this.state.relationdetaillist;
        let index = 0;
        relationdetaillist.forEach((item, i) => {
            if (item.productId == record.productId) index = i;
        })
        relationdetaillist.splice(index, 1);
        this.setState({ relationdetaillist })
    }

    //新增/编辑商品关联
    AddProductRelation() {
        //判断 保存/修改 只请求一次
        if (this.state.addIndex == 0) {
            if (this.state.relationdetaillist.length == 0) {
                return message.warning('请先选择商品再操作！', 2);
            } else {
                //判断是新增还是编辑
                let urlAdd = this.state.relationid == 0 ? "/relations/add" : "/relations/update";
                this.props.form.validateFields((err, values) => {
                    //console.log(err,values)
                    if (!err) {
                        //正则 排序序号是否重复
                        if (this.state.isexistence == '') {
                            const form = this.props.form;
                            this.state.addIndex++;//保存按钮点击次数+1
                            const productList = this.state.relationdetaillist.map(item => {
                                return {
                                    productId: item.productId,
                                    relationSort: item.relationSort,
                                    relationSpec: item.relationSpec
                                }
                            })
                            $.ajax({
                                url: `${config.JuseProduct}${urlAdd}`,
                                type: "post",
                                headers: {
                                    'Authorization': 'Bearer ' + token,
                                },
                                data: {
                                    relationId: this.state.relationid,
                                    relationName: form.getFieldValue('txt_RelationName') ? form.getFieldValue('txt_RelationName') : '',
                                    state: this.state.checked == true ? 1 : 0,
                                    productList
                                },
                                async: true,
                                success: res => {
                                    console.log('关联', res)
                                    if (res.code === 200) {
                                        if (this.state.relationid == 0) {
                                            message.success(`关联新增成功！`);
                                        } else {
                                            message.success(`关联修改成功！`);
                                            // var path = {
                                            //     pathname: '/goodsrelevance',
                                            //     state: { pageindex: this.state.pageindex },
                                            // };
                                            // hashHistory.push(path);
                                        }
                                        location.hash = "/goodsrelevance";
                                    } else if (res.code === 202) {
                                        message.config({
                                            top: 50,
                                        });
                                        message.warning('最多关联10个商品', 2);
                                        this.setState({ addIndex: 0 });
                                    } else if (res.code === 203) {
                                        message.config({
                                            top: 50,
                                        });
                                        message.warning('此关联名已存在，请重新操作！', 2);
                                        this.setState({ addIndex: 0 });
                                    } else {
                                        message.config({
                                            top: 50,
                                        });
                                        message.error('遇到网络问题，请重新操作！', 2);
                                        this.setState({ addIndex: 0 });
                                    }
                                }
                            });
                        } else {
                            message.error('已存在该序号', 2);
                        }
                    }
                });
            }
        }
    }

    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const columns = [{
            title: '排序',
            dataIndex: '',
            render: (text, record) => {
                return <div>
                    {/* <InputNumber min={1} max={10} step={1} value={record.relationsort} onChange={this.numberChange.bind(this, record)} /> */}
                    <FormItem>
                        {
                            getFieldDecorator(`txt_RelationSort${record.productId}`, {
                                rules: [{ required: false, whitespace: true, message: '请输入1-10的正整数' }],
                                initialValue: record.relationSort == null ? '' : "" + record.relationSort,
                            })(
                                <Input className='addetd-a-r' onChange={this.numberChange.bind(this, record)} maxLength='2' />
                            )
                        }
                    </FormItem>
                </div>
            },
            width: 100
        }, {
            title: '商品ID',
            dataIndex: 'productId',
            width: 50
        }, {
            title: '商品信息',
            dataIndex: '',
            render: (text, record) => {
                return <div>
                    <p>药品名称：{record.productName}&nbsp;&nbsp;规格：{record.specification}</p><p>通用名称：{record.genericName}&nbsp;&nbsp;品牌：{record.brandName}</p>
                </div>
            },
            width: 180
        }, {
            title: '商品图片',
            dataIndex: '',
            render: (text, record) => {
                return <img src={record.imageUrl + record.listImage} style={{ width: "40px" }} />
            },
            width: 100
        }, {
            title: '商品价格',
            dataIndex: '',
            render: (text, record) => {
                return <div><p>零售价：{record.retailp}</p><p>商城价：{record.marketPrice}</p></div>
            },
            width: 70
        }, {
            title: '标签',
            dataIndex: 'tagList',
            render: (text, record) => {
                return <div>{text.map(item => item.tagName).join(',')}</div>
            },
            width: 100
        }, {
            title: '商品状态',
            dataIndex: 'saleStatus',
            render: (text, record) => {
                return <div>{text == 1 ? "上架区" : "下架区"}</div>
            },
            width: 100
        }, {
            title: '产品规格',
            dataIndex: '',
            render: (text, record) => {
                return <div>
                    {/* <Input className='addetd-a-r' value={record.relationspecification} onChange={this.relationspeciChange.bind(this, record)} /> */}
                    <FormItem>
                        {
                            getFieldDecorator(`txt_RelationSpecification${record.productId}`, {
                                rules: [{ required: true, whitespace: true, min: 1, max: 24, message: '关联规格长度为1-24' }],
                                initialValue: record.relationSpec,
                            })(
                                <Input className='addetd-a-r' onChange={this.relationspeciChange.bind(this, record)} />
                            )
                        }
                    </FormItem>
                </div>
            },
            width: 200
        },
        {
            title: '操作',
            dataIndex: '',
            render: (text, record) => {
                return <Popconfirm title="确认将该商品移除?" onConfirm={this.confirmRelation.bind(this, record)} okText="Yes" cancelText="No">
                    <a href="#">移除</a>
                </Popconfirm>
            },
            width: 100
        }];
        const dataList = this.state.relationdetaillist.map((item, index) => {
            item.key = index
            return item
        })
        return (
            <Form>
                <div className='goodsrelation-label'>
                    <div className='goods-label-cont clearfix'>
                        <div className='goods-label-cont-nav clearfix'>
                            <Breadcrumb separator=">">
                                <Breadcrumb.Item>首页</Breadcrumb.Item>
                                <Breadcrumb.Item>商品管理</Breadcrumb.Item>
                                <Breadcrumb.Item>商品关联管理</Breadcrumb.Item>
                                <Breadcrumb.Item>{this.state.relationid == "0" ? "新增" : "编辑"}</Breadcrumb.Item>
                            </Breadcrumb>
                        </div>
                        <div className='member-content-Search clearfix goodrelation'>
                            <div className='addetd addetd1'>
                                <FormItem>
                                    {
                                        getFieldDecorator('txt_RelationName', {
                                            rules: [{ required: true, whitespace: true, min: 0, max: 32, message: '关联名长度为1-32' }],
                                        })(
                                            <Input className='addetd-a-r' addonBefore="关联名" placeholder="请输入" />
                                        )
                                    }
                                </FormItem>
                            </div>
                            <div className='addetd addetd1'>
                                是否开启：
                                <Checkbox checked={this.state.checked}
                                    onChange={this.onChangeRelation.bind(this)}
                                />
                            </div>

                            <div className='goods-label-tabletr' style={{ float: 'right' }}>
                                <Button className='goods-label-table-app' icon="plus" onClick={this.addProductModal.bind(this)} >新增</Button>
                            </div>
                        </div>
                        <div className='goods-label-tabletr' style={{ float: 'left' }}>
                            关联商品：
                            </div>
                        <div className='goods-label-table clearfix'>
                            <Table
                                columns={columns}
                                dataSource={dataList}
                                pagination={false}
                                bordered
                            />
                        </div>
                        <div style={{ float: 'right', marginTop: '30px', marginLeft: "20px" }}><Link to="/goodsrelevance"><Button>取消</Button></Link></div>
                        <div style={{ float: 'right', marginTop: '30px' }}><Button className='goods-label-table-app' type="primary" onClick={this.AddProductRelation.bind(this)} >保存</Button></div>
                        <RelationProduct
                            ref='relationproduct'
                            visible={this.state.productvisible}
                            products={this.state.products}
                            relationid={this.state.relationid}
                            addProduct={this.addProduct.bind(this)}
                            cancelProduct={this.cancelProduct.bind(this)}
                        />
                    </div>
                </div>
            </Form>
        )
    }
}

const Goodsrelevance = Form.create()(RegForm);
export default Goodsrelevance;